package center

import (
	_ "3rdparty/go-mysql-driver"
	"database/sql"
	"fmt"
	"log"
	"os"
)

type DBcenter struct {
	errLog *log.Logger
	db     *sql.DB
}

func newDB(cfg *ServerConfig) *DBcenter {
	dbcenter := new(DBcenter)
	dbcenter.errLog = log.New(os.Stderr, "", log.Ldate|log.Ltime|log.Lshortfile)
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&timeout=30s", cfg.DBUser, cfg.DBPassword, cfg.DBIP, cfg.DBPort, cfg.DBName)
	log.Printf("MySQL DSN: %s", dsn)
	var err error
	dbcenter.db, err = sql.Open("mysql", dsn)
	if err == nil {
		dbcenter.db.SetMaxIdleConns(50)
		log.Print("MySQL init succeed!")
		return dbcenter
	}
	dbcenter.errLog.Print(err)
	return nil

}

//func InitLog() {
//	logfile, err := os.OpenFile("F:/test.log", os.O_RDWR|os.O_CREATE, 0)
//	if err != nil {
//		fmt.Printf("%s\r\n", err.Error())
//		os.Exit(-1)
//	}
//	defer logfile.Close()
//	logger := log.New(logfile, "\r\n", log.Ldate|log.Ltime)
//	logger.Println("hello!!")
//	logger.Print("oh....")
//}
func (h *DBcenter) Read(SQL string, args ...interface{}) (rows *sql.Rows, err error) {
	log.Printf(SQL)
	rows, err = h.db.Query(SQL, args...)
	if err == nil && rows != nil {
		return rows, err
	}
	log.Print(err)
	return rows, err
}

//insert,update,delete all belongs to "Change"
func (h *DBcenter) Change(SQL string, args ...interface{}) (sql.Result, error) {
	log.Print(SQL)
	result, err := h.db.Exec(SQL, args...)
	if err != nil {
		log.Print(err)
		return result, err
	}
	if result == nil {
		log.Print("db no change by:", SQL)
		return result, err
	}
	return result, err
}
func (h *DBcenter) Close() {
	if h.db != nil {
		h.db.Close()
	}
}
